<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html" ; charset="utf-8" />
    <title>宏宇教育信息采集</title>
    <link href="./index.css" rel="stylesheet" type="text/css" />
  </head>

  <style>
    /* .id-front .el-upload--picture-card, .id-back .el-upload--picture-card, .cun1 .el-upload--picture-card, .cun2 .el-upload--picture-card, .cun1 .el-upload--picture-card, .cun1 .el-upload--picture-card {
        display: none;
    } */
    .hide .el-upload--picture-card {
      display: none;
    }
    .box-card {
      margin: 20px 0;
    }
  </style>

  <body>
    <div id="app">
      <app-base-information
        :file-map="fileList"
        ref="baseInfo"
        @on-get-info="getInfoByIdNoHandler"
      ></app-base-information>
      <app-education-level
        ref="educationLevel1"
        :file-map="fileList"
        :levelnum="1"
        :level-list="levelList"
      ></app-education-level>
      <app-education-level
        ref="educationLevel2"
        :file-map="fileList"
        :levelnum="2"
        :level-list="levelList"
      ></app-education-level>
      <app-certificate :file-map="fileList" ref="certificate"></app-certificate>
      <app-education
        :level-list="levelList"
        v-if="isEducation"
        ref="education"
      ></app-education>
      <app-occupation v-if="isOccupation" ref="occupation"></app-occupation>
      <app-title v-if="isTitle" ref="title"></app-title>
      <app-train v-if="isTrain" ref="train"></app-train>
      <app-cost-information
        :fee-len="isEducation ? 4 : 2"
        ref="costInfo"
        :title="costTitle"
      ></app-cost-information>
      <el-row>
        <el-col style="display: flex; justify-content: center">
          <el-button
            :disabled="isSubmit"
            @click="handleValid('save')"
            type="primary"
            >保存</el-button
          >
          <el-button
            :disabled="isSubmit"
            @click="handleValid('submit')"
            type="primary"
            >提交</el-button
          >
        </el-col>
      </el-row>
    </div>

    <script src="../../../js/jquery.js"></script>
    <script src="../../../js/common.js"></script>
    <script src="../../../js/vue.js"></script>
    <script src="../../../js/element.js"></script>
    <script src="./components/BaseInformation.js"></script>
    <script src="./components/EducationLevel.js"></script>
    <script src="./components/Certificate.js"></script>
    <script src="./components/Education.js"></script>
    <script src="./components/Occupation.js"></script>
    <script src="./components/Title.js"></script>
    <script src="./components/Train.js"></script>
    <script src="./components/CostInformation.js"></script>

    <script>
      const app = new Vue({
        el: "#app",
        created() {
          this.infoName = getQuery("trainType");
        },
        mounted() {
          this.getPageTitle();
          this.getEducationOption();
        },
        data: {
          isSubmit: false,
          levelList: [],
          // 当前页面的名称
          infoName: "",
          id: "",
          genId: "",
          // type: "",
          action: "",
          idNo: "",
          studyId: "",
          baseInfoMap: new Map([
            ["name", "name"],
            ["phoneNum", "phone"],
            ["idNo", "idNum"],
            ["nation", "nationality"],
            ["sex", "gender"],
            ["birthday", "birthday"],
            ["address", "address"],
            ["email", "email"],
            ["qqNumber", "qq"],
            ["workAdress", "work"],
          ]),
          educationLevel: new Map([
            ["major", "discipline"],
            ["educationName", "level"],
            ["studyMode", "path"],
            ["graduateSchool", "school"],
            ["graduateTime", "time"],
            ["certificateNumber", "cerNum"],
          ]),
          educationMap: new Map([
            ["studyMode", "pathLabel"],
            ["educationName", "levelLabel"],
            ["schoolName", "schoolLabel"],
            ["majorName", "discipline"],
            ["batch", "batch"],
          ]),
          occupationKeys: [
            "professionalTypes",
            "majorName",
            "batch",
            "applyExplain",
          ],
          titleKeys: [
            "professionalLevel",
            "professionalSeries",
            "majorName",
            "batch",
          ],
          trainKeys: [
            "applyProject",
            "examCourse",
            "classs",
            "applyAssist",
            "startDate",
            "endDate",
            "batch",
          ],
          feesMap: new Map([
            ["stage", "stage"],
            ["amount", "fee"],
            ["term", "feeDate"],
            ["flag", "isFee"],
            ["receiptStatus", "receipt"],
            ["receiptNo", "receiptNum"],
          ]),
          feeMap: new Map([
            ["otherFee", "otherFee"],
            ["paidinFee", "training"],
            ["explains", "description"],
            ["allFee", "total"],
            ["preferentialFee", "discount"],
            ["realPayFee", "paid"],
          ]),
          fileList: [],
        },
        computed: {
          isEducation() {
            return this.infoName === "education";
          },
          isOccupation() {
            return this.infoName === "occupation";
          },
          isTitle() {
            return this.infoName === "title";
          },
          isTrain() {
            return this.infoName === "train";
          },
          costTitle() {
            const map = {
              education: "学历",
              occupation: "职业",
              title: "职称",
              train: "培训",
            };
            return map[this.infoName];
          },
        },
        methods: {
          // 根据身份证号获取数据并填写
          getInfoByIdNoHandler(data) {
            console.log(`data>>>>>>`, data);
            this.fileList = data.studentCards;

            const {
              educationLevel1: educationLevelInfo,
              educationLevel2: educationLevelInfo2,
            } = this.getRefs("formData");

            for (item of this.educationLevel) {
              educationLevelInfo[item[1]] = data.student[item[0]];
              educationLevelInfo2[item[1]] = data.student[item[0] + "2"];
            }
          },
          getPageTitle() {
            // 根据查询字符串info，来判断显示哪个报考信息
            const type = getQuery("trainType");
            switch (type) {
              case "education":
                localStorage.setItem("name", "学生管理/学历提升");
                break;
              case "occupation":
                localStorage.setItem("name", "学生管理/职业技能");
                break;
              case "title":
                localStorage.setItem("name", "学生管理/职称评审");
                break;
              case "train":
                localStorage.setItem("name", "学生管理/执业资格");
                break;
            }
          },
          handleValid(flag) {
            this.action = flag;
            const errMap = {
              baseInfo: "基本信息未填写完成",
              educationLevel1: "第一学历未填写完成",
              educationLevel2: "第二学历未填写完成",
              certificate: "证书未填写完成",
              costInfo: "学历缴费信息未填写完成",
            };
            const infoMap = {
              education: {
                type: "education",
                msg: "学历报考信息未填写完成",
              },
              occupation: {
                type: "occupation",
                msg: "职业报考信息未填写完成",
              },
              title: {
                type: "title",
                msg: "职称报考信息未填写完成",
              },
              train: {
                type: "train",
                msg: "培训报考信息未填写完成",
              },
            };
            const formRef = this.getRefs("$refs");
            Object.keys(formRef).forEach((key) => {
              if (formRef[key] === undefined) {
                delete formRef[key];
              }
            });
            const formPList = Object.keys(formRef).map((item) => {
              return new Promise((resolve, reject) => {
                formRef[item] &&
                  formRef[item].form.validate((valid) => {
                    if (valid) {
                      resolve();
                    } else {
                      const msg =
                        this.infoName === item
                          ? infoMap[this.infoName].msg
                          : errMap[item];
                      reject(msg);
                    }
                  });
              });
            });

            Promise.all(formPList)
              .then((item) => {
                this.handleSave();
              })
              .catch((error) => {
                this.$message({
                  message: error,
                  type: "error",
                });
              });
          },
          getRefs(key = "") {
            const {
              baseInfo = {},
              educationLevel1 = {},
              educationLevel2 = {},
              certificate = {},
              costInfo = {},
              education = {},
              occupation = {},
              title = {},
              train = {},
            } = this.$refs;

            return {
              baseInfo: baseInfo[key],
              educationLevel1: educationLevel1[key],
              educationLevel2: educationLevel2[key],
              certificate: certificate[key],
              costInfo: costInfo[key],
              education: education[key],
              occupation: occupation[key],
              title: title[key],
              train: train[key],
            };
          },
          handleSave() {
            const {
              baseInfo,
              educationLevel1,
              educationLevel2,
              certificate,
              costInfo,
              education,
              occupation,
              title,
              train,
            } = this.getRefs("formData");

            const student = {
              pid: JSON.parse(localStorage.getItem("userInfo")).account.split(
                "-"
              )[1],
              // commitFlag: flag === "save" ? 0 : 1,
              name: baseInfo.name,
              phoneNum: baseInfo.phone,
              idNo: baseInfo.idNum,
              nation: baseInfo.nationality,
              sex: baseInfo.gender,
              birthday: baseInfo.birthday,
              address: baseInfo.address,
              email: baseInfo.email,
              qqNumber: baseInfo.qq,
              workAdress: baseInfo.work,
              // 学历1
              major: educationLevel1.discipline,
              educationName: educationLevel1.level,
              studyMode: educationLevel1.path,
              graduateSchool: educationLevel1.school,
              graduateTime: educationLevel1.time,
              certificateNumber: educationLevel1.cerNum,
              // 学历2
              major2: educationLevel2.discipline,
              educationName2: educationLevel2.level,
              studyMode2: educationLevel2.path,
              graduateSchool2: educationLevel2.school,
              graduateTime2: educationLevel2.time,
              certificateNumber2: educationLevel2.cerNum,
            };

            const mobile = JSON.parse(
              localStorage.getItem("userInfo")
            ).mobile.slice(7);
            // this.type !== 'edit' && (this.genId = getId() + mobile);
            this.genId = getId() + mobile;
            const data = {
              student: [student],
            };
            if (education) {
              data.studentEducations = [
                {
                  studyMode: education.pathLabel,
                  educationName: education.levelLabel,
                  schoolName: education.schoolLabel,
                  majorName: education.discipline,
                  batch: education.batch,
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            if (occupation) {
              data.studentOccupations = [
                {
                  ...occupation,
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            if (title) {
              data.studentTitles = [
                {
                  ...title,
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            if (train) {
              train.examCourse = train.examCourse.toString();
              data.studentTrains = [
                {
                  ...train,
                  teacherId: JSON.parse(
                    localStorage.getItem("userInfo")
                  ).account.split("-")[1],
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            this.save(data);
          },
          save(data) {
            $.ajax({
              url: baseUrl + "studentInfo/saveStudentInfo",
              method: "Post",
              contentType: "application/json;charset=UTF-8",
              data: JSON.stringify({
                ...data,
              }),
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                if (data.code === 200) {
                  this.isSubmit = true;
                  this.id = data.message;
                  this.$message({
                    message: `${
                      this.action === "save" ? "保存成功" : "提交成功"
                    }`,
                    type: "success",
                  });
                  this.saveFee(data);
                } else {
                  this.$message({
                    message: data.message,
                    type: "error",
                  });
                }
              },
              error: (err, res, res1) => {
                this.$message({
                  message: err.responseJSON.message || "网络错误",
                  type: "error",
                });
              },
            });
          },
          saveFee() {
            const { costInfo } = this.getRefs("formData");
            // const costInfo = this.$refs.costInfo.formData;
            const fees = costInfo.fees.map((item) => {
              const data = {
                studentId: this.id,
                teacherId: JSON.parse(
                  localStorage.getItem("userInfo")
                ).account.split("-")[1],
                commitFlag: this.action === "save" ? 0 : 1,
                businessProgress: 0,
                trainType: this.infoName,
                // 报考专业
                studyId: this.genId,
                // 期数
                stage: item.stage || "",
                // 缴费日期
                term: item.feeDate,
                // 缴费金额
                amount: item.fee == 0 ? 0 : item.fee || "",
                // 是否已缴费
                flag: item.isFee,
                // 收据状态
                receiptStatus: item.receipt,
                // 收据编号
                receiptNo: item.receiptNum,
                // 费用类别
                otherName: costInfo.otherName,
                // 报名费
                otherFee: costInfo.otherFee,
                // 培训费
                paidinFee: costInfo.training,
                // 说明
                explains: costInfo.description,
                // 总费用
                allFee: costInfo.total,
                // 优惠费用
                preferentialFee: costInfo.discount,
                // 实缴费用
                realPayFee: costInfo.paid,
              };
              // this.type === 'edit' && (data.id = item.id)
              return data;
            });

            $.ajax({
              url: baseUrl + "studentInfo/saveStudentFees",
              method: "post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              contentType: "application/json",
              data: JSON.stringify(fees),
              success: (data) => {
                this.saveFile();
              },
            });
          },
          saveFile() {
            if (!this.id) return;
            const { certificate: certificateFromData } =
              this.getRefs("formData");
            const {
              baseInfo,
              educationLevel1,
              educationLevel2,
              certificate: certificateFileDic,
            } = this.getRefs("fileDic");
            // const certificateFromData = this.$refs.certificate.formData;
            // const certificateFileDic = this.$refs.certificate.fileDic;
            // const baseInfo = this.$refs.baseInfo.fileDic;
            // const educationLevel1 = this.$refs.educationLevel1.fileDic;
            // const educationLevel2 = this.$refs.educationLevel2.fileDic;
            const formData = new FormData();

            for (item of baseInfo) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of educationLevel1) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of educationLevel2) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of certificateFileDic) {
              formData.append(
                "propertys",
                `${certificateFromData[item[0]]}|${item[0]}`
              );
              formData.append("files", item[1]);
            }
            formData.append("studentId", this.id);
            formData.append("studyId", this.genId);
            formData.append("trainType", this.infoName);
            $.ajax({
              url: baseUrl + "studentInfo/uploadStuCertificate",
              method: "post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              data: formData,
              processData: false,
              contentType: false,
              mimeType: "multipart/form-data",
              success: function (data) {
                window.location.href = "../hotel/studentSearch.html";
              },
            });
          },
          getEducationOption() {
            $.ajax({
              url: baseUrl + "education/queryEducationList",
              async: false,
              method: "Post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                this.levelList = data;
                console.log(`this.levelList`, this.levelList);
              },
            });
          },
        },
      });
    </script>
  </body>
</html>
